package org.steven.crm.core.auth;

import org.steven.crm.core.auth.dto.GrantTokenRequest;
import org.steven.crm.core.exception.BusinessErrors;
import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.accesstoken.AccessTokenService;
import org.steven.crm.core.service.accesstoken.ClientService;

import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/1/10 17:13
 * @Version 1.0
 */

public abstract class AuthHandler {
    private static AccessTokenService accessTokenService = new AccessTokenService();
    private static ClientService clientService = new ClientService();

    public Map<String, String> grant(GrantTokenRequest grantTokenRequest) throws Exception {
        Map<String, String> client = clientService.read(grantTokenRequest.getClientId());
        if (client.isEmpty()) {
            throw new ServiceException(BusinessErrors.AUTH_WRONG);
        }

        return createToken(client, grantTokenRequest);
    }

    public  abstract Map<String, String> createToken(Map<String, String> client, GrantTokenRequest grantTokenRequest) throws Exception;

    public  Map<String, String> validate(String token) throws Exception {
        Map<String, String> accessToken = accessTokenService.validate(token);

        return this.authorize(accessToken);
    }

    protected abstract Map<String, String> authorize(Map<String, String> accessToken) throws Exception;

}
